using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class EnemyManagerScript : MonoBehaviour
{
    private TimeTicker timeTicker = new TimeTicker(1);
    private GameObject enemyPrefab = null;
    //enemies数组
    private Queue<GameObject> enemies = new Queue<GameObject>();
    public HeroScript hero;
    // Start is called before the first frame update
    void Start()
    {
        //获取enemies AssetBundle
        var myLoadedAssetBundle
            = AssetBundle.LoadFromFile(Path.Combine(Application.dataPath, "AssetBundles/enemies"));
        //加载enemies AssetBundle中的Enemy预制体
        enemyPrefab = myLoadedAssetBundle.LoadAsset<GameObject>("Enemy");
        //卸载enemies AssetBundle
        myLoadedAssetBundle.Unload(false);//如果不卸载，AssetBundle会一直占用内存
    }

    // Update is called once per frame
    void Update()
    {
        float dt = Time.deltaTime;
        timeTicker.Tick(dt);
        if (timeTicker.IsTimeUp())
        {
            CreateEnemy();
        }
        if (enemies.Count > 0)
        {
            //遍历enemies数组
            foreach (var enemy in enemies)
            {
                //调用EnemyScript的Move方法
                enemy.GetComponent<EnemyScript>().Move();
            }
        }
    }
    private void CreateEnemy()
    {
        //360度随机角度
        float angle = Random.Range(0, 360);
        //中心为hero半径为2的圆上的随机点
        Vector3 position = hero.GetPosition() + new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0).normalized * 3;
        //实例化Enemy预制体
        var instance = Instantiate(enemyPrefab);
        //设置Enemy预制体的位置
        instance.transform.position = position;
        //设置Enemy预制体的parent
        instance.transform.parent = transform;
        //设置Enemy预制体的hero
        instance.GetComponent<EnemyScript>().SetHero(hero);
        //将Enemy预制体添加到enemies数组
        enemies.Enqueue(instance);
    }

}
